home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3425 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  84 lines

  1. Newsgroups: comp.lang.c
  2. Path: gail.ripco.com!mambuhl
  3. From: mambuhl@ripco.com (Martin Ambuhl)
  4. Subject: Re: Can a function return
  5. X-Nntp-Posting-Host: foley.ripco.com
  6. Message-ID: <DLwwKu.3DA@rci.ripco.com>
  7. Sender: usenet@rci.ripco.com (Net News Admin)
  8. Organization: Ripco Internet BBS Chicago
  9. Date: Sun, 28 Jan 1996 22:17:18 GMT
  10. X-Ident-Sender: mambuhl
  11.  
  12. "John D. Hourihane" <hourihaj@iol.ie> in <4ebaaa$jh6@barnacle.iol.ie>
  13. asks:
  14.  
  15. >I am trying to write a function which will return a pointer to a function,
  16. >but I'm having no luck.
  17.  
  18. See the suggestion below in the code.
  19.  
  20. >The toy program below illustrates (I hope) what I want to be able to do,
  21. >but as it stands it won't compile for me. The idea is that the call to
  22. >'(pick(ADD))' will return a pointer to the 'add' function which is then
  23. >dereferenced and used.
  24.  
  25. >But like I say, it doesn't compile. It complains 'Declaration terminated
  26. >incorrectly' as I declare 'pick'. I'm using Turbo C/C++.
  27.  
  28. >Any reply, posted here or by email, would be great.
  29.  
  30. >PHiL
  31.  
  32. >/* The toy program, to use a function that returns a
  33. > * pointer to a function.
  34. > */
  35.  
  36. >#include <stdio.h>
  37.  
  38. >#define ADD                     0
  39. >#define MULTIPLY        1
  40.  
  41. >int add(int x, int y);
  42. >int multiply(int x, int y);
  43.  
  44. >/* pick returns a pointer to a function which will operate on two integers */
  45.  
  46. REPLACE:
  47. >(int f(int, int)) *pick(int s);
  48. WITH:
  49. typedef int (*PFNC) (int, int); /* mha */
  50. PFNC pick(int s);               /* mha */
  51.  
  52. >int main()
  53. >{
  54. >        printf("5 + 4 = %d\n", (*(pick(ADD)))(5,4));
  55. >        printf("5 * 4 = %d\n", (*(pick(MULTIPLY)))(5,4));
  56.  
  57. There is nothing wrong with the above, but neither is there anything
  58. wrong with the (easier to my eye):
  59.     printf("5 + 4 = %d\n", pick(ADD) (5, 4));       /* mha */
  60.     printf("5 * 4 = %d\n", pick(MULTIPLY) (5, 4));  /* mha */
  61.  
  62. >        return 0;
  63. >}
  64.  
  65. >int add(int x, int y)
  66. >{       return x + y; }
  67.  
  68. >int multiply(int x, int y)
  69. >{       return x * y; }
  70.  
  71. REPLACE:
  72. >(int f(int, int)) *pick(int s)
  73. WITH:
  74. PFNC pick(int s)    /* mha */
  75.  
  76. >{       if (s == ADD)
  77. >                return add;
  78. >        return multiply;
  79. >}
  80.                                                        
  81. --
  82. * Martin Ambuhl       net: mambuhl@ripco.com
  83. * Chicago, IL (USA)    
  84.